JS - move grid cells using JS

revision:


Content

CSS-based order of grid cells JS-based order of grid cells add a class to grid items and move them to the front of the grid reorder DOM elements dynamically clone selected items into a new grid container move selected items to a new grid


CSS-based order of grid cells

top

1
2
3
4
code:
            <div class="grid_A">
                <div class="cell">1</div>
                <div class="cell">2</div>
                <div class="cell selected">3</div>
                <div class="-cell">4</div>
            </div>
            <style>
                .grid_A { display: grid; grid-template-columns: repeat(2, 1fr); gap: 1vw;}
            .cell { order: 1; /* Default order */ width: 2vw; height: 2vw; border: 0.2vw dashed green;}
            .selected {order: -1; /* Moves to the front/top */}
            </style>
        

The "order" property affects visual order only, not DOM order (which matters for accessibility and tab navigation). For better accessibility, consider reordering the DOM elements directly via JavaScript if visual and semantic order must match.


JS-based order of grid cells

top

1
2
3
4
5
6
7
code:
           <div class="grid_B">
                <div class="cell_B">1</div>
                <div class="cell_B">2</div>
                <div class="cell_B selected_B">3</div>
                <div class="cell_B">4</div>
                <div class="cell_B">5</div>
                <div class="cell_B selected_B">6</div>
                <div class="-cell_B">7</div>
            </div>
            <style>
                .grid_B { display: grid; grid-template-columns: repeat(2, 1fr); gap: 1vw;}
                .cell_B {width: 2vw; height: 2vw; border: 0.2vw dashed skyblue;}
            </style>
            <script>
                // Move all selected cells to the top
                const container = document.querySelector('.grid_B');
                const selected = Array.from(container.querySelectorAll('.selected_B'));

                selected.forEach(el => {
                    container.prepend(el); // Moves to the top
                });
            </script>
        

add a class to grid items and move them to the front of the grid

top

1 - adding a class

2 - reordering the DOM so that elements with that class appear first — causing CSS grid to place them at the beginning (top-left) if you're using auto-placement.

Avoid using explicit grid-column/grid-row; rely on auto-placement so DOM order controls visual order.

A
B
C
D
E
F
code:
            <div class="grid1">
                <div id="grid_C" class="grid_C">
                    <div class="item">A</div>
                    <div class="item">B</div>
                    <div class="item">C</div>
                    <div class="item">D</div>
                    <div class="item">E</div>
                    <div class="item">F</div>
                </div>
                <style>
                    .grid_C { display: grid; grid-template-columns: repeat(auto-fill, minmax(5vw, 1fr)); gap: 0.9vw; padding: 1vw; }
                    .item {background: #e0e0e0; border: 0.1vw solid #ccc; display: flex; align-items: center; justify-content: center; 
                        height: 4vw;  font-size: 1.5vw;  cursor: pointer; transition: all 0.3s ease; }
                    .item.selected { background: gold; border-color: orange; transform: scale(1.05); z-index: 10; position: relative;}
                </style>
                <script>
                    const grid = document.getElementById('grid_C');
                    grid.addEventListener('click', (e) => {
                        const item = e.target.closest('.item');
                        if (!item) return;

                        // Toggle 'selected' class
                        item.classList.toggle('selected');

                        // Reorder: move all selected items to the front
                        reorderSelectedToFront();
                    });

                    function reorderSelectedToFront() {
                        const selected = Array.from(grid.querySelectorAll('.item.selected'));
                        const nonSelected = Array.from(grid.querySelectorAll('.item:not(.selected)'));

                        // Clear current content
                        grid.innerHTML = '';

                        // Append selected first (preserving their selection order)
                        selected.forEach(el => grid.appendChild(el));
                        // Then append the rest
                        nonSelected.forEach(el => grid.appendChild(el));
                    }
                </script>

        

reorder DOM elements dynamically

top

Use the DOM reordering method ("replaceChildren" or "prepend/append") for a clean, dynamic, and accessible solution that updates the grid layout in real time as the user selects or deselects cells.

1
2
3
4
5
6
7
8
9
10
code:
            <div class="grid_D" id="grid_D">
                <div class="cell_D" data-id="1">1</div>
                <div class="cell_D" data-id="2">2</div>
                <div class="cell_D" data-id="3">3</div>
                <div class="cell_D" data-id="4">4</div>
                <div class="cell_D" data-id="5">5</div>
                <div class="cell_D" data-id="6">6</div>
                <div class="cell_D" data-id="7">7</div>
                <div class="cell_D" data-id="8">8</div>
                <div class="cell_D" data-id="9">9</div>
                <div class="cell_D" data-id="10">10</div>
            </div>
            <style>
                .grid_D {display: grid; grid-template-columns: repeat(auto-fill, minmax(3vw, 1fr)); gap: 1vw; padding: 0.5vw;}
                .cell_D {padding: 1vw; width: 2vw; height: 2vw; background: orange; border: 0.1vw solid #ccc;  text-align: center;
                     cursor: pointer;
                transition: background 0.2s; }
                .cell_D.selected {background: skyblue; border-color: green; }
            </style>
            <script>
                const grid_D = document.getElementById('grid_D');
                const cells = grid_D.querySelectorAll('.cell_D');
                // Keep track of selected cell data-ids (optional, for state)
                let selectedIds = new Set();

                cells.forEach(cell => {
                cell.addEventListener('click', () => {
                    cell.classList.toggle('selected');
                    
                    // Update selection set
                    const id = cell.dataset.id;
                    if (cell.classList.contains('selected')) {
                        selectedIds.add(id);
                        } else {
                            selectedIds.delete(id);
                            }

                            // Reorder: move all selected cells to the top
                            const selectedCells = Array.from(grid_D.querySelectorAll('.selected'));
                            const unselectedCells = Array.from(grid_D.querySelectorAll('.cell:not(.selected)'));

                            // Clear container
                            grid_D.replaceChildren(...selectedCells, ...unselectedCells);
                        });
                    });
            </script>
        

clone selected items into a new grid container

top

non-destructive; the original grid stays intact

Steps:

1: Create a new container (e.g., #selected-preview).
2/ On selection change, clear it and clone selected items into it.
3/ Style the new container as a grid.

A
B
C
code:
            <div>
                <!-- Original grid -->
                <div class="grid_E" id="originalGrid">
                    <div class="item_E" data-id="1">A</div>
                    <div class="item_E" data-id="2">B</div>
                    <div class="item_E" data-id="3">C</div>
                </div>
                <!-- New grid for selected items -->
                <div class="grid_E" id="selectedGrid"></div>
            </div>
            <style>
                .grid_E { display: grid; grid-template-columns: repeat(auto-fill, minmax(80px, 1fr)); gap: 8px;}
                .item_E {padding: 12px; background: #eee; cursor: pointer;}
                .item_E.selected_E { background: lightblue;}


            </style>
            <script>
                const originalGrid = document.getElementById('originalGrid');
                const selectedGrid = document.getElementById('selectedGrid');

                // Make items selectable
                originalGrid.addEventListener('click', (e) => {
                    if (e.target.classList.contains('item_E')) {
                        e.target.classList.toggle('selected_E');
                        updateSelectedGrid();
                    }
                });

                function updateSelectedGrid() {
                    // Clear the selected grid
                    selectedGrid.innerHTML = '';

                    // Clone all selected items and append to new grid
                    const selected = originalGrid.querySelectorAll('.item_E.selected_E');
                    selected.forEach(item => {
                        const clone = item.cloneNode(true); // true = deep clone
                        // Optional: remove click handler or modify clone
                        selectedGrid.appendChild(clone);
                        // originalGrid.style.display = "none";
                    });
                }
            </script>
        

move selected items to a new grid

top

Destructive: removes from original grid.

A
B
C
code:
            <div>
                <!-- Original grid -->
                <div class="grid_F" id="originalGrid_F">
                    <div class="item_F" data-id="4">A</div>
                    <div class="item_F" data-id="5">B</div>
                    <div class="item_F" data-id="6">C</div>
                </div>
                <!-- New grid for selected items -->
                <div class="grid_F" id="selectedGrid_F"></div>
            </div>
            <style>
                .grid_F { display: grid; grid-template-columns: repeat(auto-fill, minmax(80px, 1fr)); gap: 8px;}
                .item_F {padding: 12px; background: grey; color: white; cursor: pointer;}
                .item_F.selected_F { background: lighgreen;}
            </style>
            <script>
                const originalGrid_F = document.getElementById('originalGrid_F');
                const selectedGrid_F = document.getElementById('selectedGrid_F');

                // Make items selectable
                originalGrid_F.addEventListener('click', (e) => {
                    if (e.target.classList.contains('item_F')) {
                        e.target.classList.toggle('selected_F');
                        moveSelectedToNewGrid();
                    }
                });

                function moveSelectedToNewGrid() {
                    selectedGrid_F.innerHTML = ''; // or keep existing?
                    const selected = originalGrid_F.querySelectorAll('.item_F.selected_F');
                    selected.forEach(item => {
                        selectedGrid_F.appendChild(item); // This MOVEs the element
                        item.classList.remove('selected_F'); // optional
                    });
                }
            </script>